/*
   Copyright 2009 Marcin Szczepanski, webqem (marcins@gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package webqem.utils
{
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;

	public class OrderedArray extends Proxy
	{
		private var _elements:Array;
        private var _insertionHint:int;
        private var _comparator:Function = function(a:*, b:*):int {
            return (b > a ? 1 : (b < a ? -1 : 0));
        };
		
		public function set comparator(value:Function):void
		{
			_comparator = value;
		}
		
		public function get comparator():Function
		{
			return _comparator;
		}
		
		public function OrderedArray(insertionHint:int = 0)
		{
			_insertionHint = insertionHint;
			_elements = new Array();
		}
		
		public function addElement(value:*):void
		{
			if(_elements.length == 0) {
				_elements.push(value);
				return;
			}
			
			if(_insertionHint == OrderedArrayInsertionHint.END) {
				var lastElement:* = _elements[_elements.length - 1];
				if(_comparator(lastElement, value) <= 0) {
					_elements.push(value);
					return;
				}
			} else if(_insertionHint == OrderedArrayInsertionHint.MIDDLE) {
				// TODO implement OrderedArrayInsertionHint.MIDDLE
			}

            var len:uint = _elements.length;
            var element:*;
            for(var i:uint = 0; i < len; i++) {
                element = _elements[i];
                if(_comparator(element, value) == 1) {
                    _elements.splice(i, 0, value); 
                    return;
                }
            }
            _elements.push(value);

		}
		
		public function getElementAt(index:uint):*
		{
			return _elements[index];	
		}
		
		public function get length():uint
		{
			return _elements.length;
		}
		
		public function removeAll():void
		{
			_elements = new Array();
		}
		
		override flash_proxy function nextNameIndex(index:int):int 
		{
	       if(index < _elements.length) {
                return index + 1; 
	       } else {
    			return 0;
	       }
		}
		
		override flash_proxy function nextValue(index:int):*
		{
			return _elements[index - 1];
		}
		
	}
}